package com.mallcloud.mall.common.data.tenant;

import cn.hutool.core.util.StrUtil;
import com.mallcloud.mall.common.core.constant.CommonConstants;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 租户上下文过滤器
 */
@Slf4j
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class TenantContextHolderFilter extends GenericFilterBean {
    private final static String UNDEFINED_STR = "undefined";

    @Override
    @SneakyThrows
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String headerTenantId = request.getHeader(CommonConstants.TENANT_ID);
        String paramTenantId = request.getParameter(CommonConstants.TENANT_ID);

        log.info("url:{},获取header中的租户ID为:{}", request.getRequestURL().toString(), headerTenantId);

        if (StrUtil.isNotBlank(headerTenantId) && !StrUtil.equals(UNDEFINED_STR, headerTenantId)) {
            TenantContextHolder.setTenantId(Long.parseLong(headerTenantId));
        } else if (StrUtil.isNotBlank(paramTenantId) && !StrUtil.equals(UNDEFINED_STR, paramTenantId)) {
            TenantContextHolder.setTenantId(Long.parseLong(paramTenantId));
        } else {
            TenantContextHolder.setTenantId(CommonConstants.TENANT_ID_1);
        }

        filterChain.doFilter(request, response);
        TenantContextHolder.clear();
    }

}
